package com.nofeng.wx.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
public class LogController {
    // 定义日志文件的路径
    private static final Path LOG_FILE_PATH = Paths.get("/apps/app.log");

    @GetMapping("/log")
    public ResponseEntity<String> getLast500LinesOfLog() throws IOException {
        // 检查文件是否存在
        if (!Files.exists(LOG_FILE_PATH)) {
            return ResponseEntity.notFound().build();
        }

        // 读取所有行
        List<String> allLines = Files.readAllLines(LOG_FILE_PATH);

        // 获取最后500行
        int maxLines = Math.min(500, allLines.size());
        List<String> last500Lines = allLines.subList(Math.max(0, allLines.size() - maxLines), allLines.size());

        // 将最后500行转换为字符串
        String last500LinesStr = String.join("\n", last500Lines);

        return ResponseEntity.ok(last500LinesStr);
    }
}
